package com.hdy.common.network;

import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import java.util.ArrayList;
import java.util.List;

public class NetworkConnectionManager {

    private static NetworkConnectionManager sInstance;
    private NetworkConnectionReceiver mNetworkReceiver;
    private List<INetworkConnectionObserver> mObservers = new ArrayList<INetworkConnectionObserver>();

    private AutoConnectNetwork mAutoConnectNetwork;

    private NetworkConnectionManager() {
        mNetworkReceiver = new NetworkConnectionReceiver();
    }

    public static NetworkConnectionManager getInstance() {
        if (sInstance == null) {
            sInstance = new NetworkConnectionManager();
        }
        return sInstance;
    }

    public void register(Context context) {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            context.registerReceiver(mNetworkReceiver, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mAutoConnectNetwork = new AutoConnectNetwork(context, true);
        mAutoConnectNetwork.onStart();
    }

    public void unregister(Context context) {
        try {
            if (mNetworkReceiver == null) {
                return;
            }
            context.unregisterReceiver(mNetworkReceiver);
            mAutoConnectNetwork.onDestroy();
            mObservers.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
        sInstance = null;
    }

    public void addNetworkConnectionObserver(INetworkConnectionObserver observer) {
        if (mObservers.contains(observer)) {
            return;
        }
        mObservers.add(observer);
    }

    public void removeNetworkConnectionObserver(INetworkConnectionObserver observer) {
        if (mObservers.contains(observer)) {
            mObservers.remove(observer);
        }
    }

    public void notifyObserver() {
        for (int i = 0; i < mObservers.size(); i++) {
            mObservers.get(i).onAvailable();
        }
    }

    public void notifyNetworkConnectChange(NetworkConnectState state) {
        for (int i = 0; i < mObservers.size(); i++) {
            mObservers.get(i).onNetworkConnectChange(state);
        }
    }

    public void notifyNetworkDisconnected() {
        for (int i = 0; i < mObservers.size(); i++) {
            mObservers.get(i).onDisconnected();
        }
    }

}
